<template>
  <div class="products-list-settings">
    <div class="page-header">
      <h1>产品列表管理</h1>
      <el-button type="primary" @click="showAddProduct">
        <el-icon><Plus /></el-icon>
        添加产品
      </el-button>
    </div>

    <!-- 产品列表 -->
    <el-card>
      <el-table 
        :data="productList" 
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="产品图片" width="100">
          <template #default="scope">
            <div class="product-image">
              <img 
                v-if="scope.row.images && scope.row.images.length > 0" 
                :src="scope.row.images[0]" 
                alt="Product Image"
              />
              <div v-else class="no-image">
                <el-icon><Picture /></el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品名称">
          <template #default="scope">
            <div class="product-names">
              <div><strong>EN:</strong> {{ scope.row.name_en }}</div>
              <div><strong>ES:</strong> {{ scope.row.name_es }}</div>
              <div><strong>JA:</strong> {{ scope.row.name_ja }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="100">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="认证" width="120">
          <template #default="scope">
            <div class="certifications">
              <el-tag 
                v-for="cert in scope.row.certifications" 
                :key="cert" 
                size="small"
                style="margin: 1px;"
              >
                {{ cert }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" />
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.isActive"
              @change="toggleProductStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="editProduct(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="text" style="color: #f56c6c;" @click="deleteProduct(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 产品编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑产品' : '添加产品'"
      width="60%"
      :before-close="handleDialogClose"
    >
      <el-form 
        ref="productFormRef" 
        :model="currentProduct" 
        :rules="productRules"
        label-width="120px"
      >
        <!-- 基础信息 -->
        <el-divider content-position="left">基础信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称(EN)" prop="name_en">
              <el-input v-model="currentProduct.name_en" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称(ES)" prop="name_es">
              <el-input v-model="currentProduct.name_es" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称(JA)" prop="name_ja">
              <el-input v-model="currentProduct.name_ja" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品分类" prop="category">
              <el-select v-model="currentProduct.category" style="width: 100%">
                <el-option 
                  v-for="cat in categories" 
                  :key="cat.id" 
                  :label="cat.name_en" 
                  :value="cat.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产品描述 -->
        <el-divider content-position="left">产品描述</el-divider>
        
        <el-form-item label="描述(EN)" prop="description_en">
          <el-input v-model="currentProduct.description_en" type="textarea" :rows="3" />
        </el-form-item>
        
        <el-form-item label="描述(ES)" prop="description_es">
          <el-input v-model="currentProduct.description_es" type="textarea" :rows="3" />
        </el-form-item>
        
        <el-form-item label="描述(JA)" prop="description_ja">
          <el-input v-model="currentProduct.description_ja" type="textarea" :rows="3" />
        </el-form-item>

        <!-- 规格信息 -->
        <el-divider content-position="left">规格信息</el-divider>
        
        <el-form-item label="规格(EN)">
          <el-input v-model="currentProduct.specifications_en" type="textarea" :rows="2" />
        </el-form-item>
        
        <el-form-item label="规格(ES)">
          <el-input v-model="currentProduct.specifications_es" type="textarea" :rows="2" />
        </el-form-item>
        
        <el-form-item label="规格(JA)">
          <el-input v-model="currentProduct.specifications_ja" type="textarea" :rows="2" />
        </el-form-item>

        <!-- 认证信息 -->
        <el-divider content-position="left">认证信息</el-divider>
        
        <el-form-item label="认证证书">
          <el-select 
            v-model="currentProduct.certifications" 
            multiple 
            style="width: 100%"
            placeholder="选择认证证书"
          >
            <el-option label="HACCP" value="HACCP" />
            <el-option label="ISO 22000" value="ISO 22000" />
            <el-option label="BRC" value="BRC" />
            <el-option label="MSC" value="MSC" />
            <el-option label="ASC" value="ASC" />
            <el-option label="BAP" value="BAP" />
            <el-option label="FDA" value="FDA" />
            <el-option label="GB" value="GB" />
          </el-select>
        </el-form-item>

        <!-- 产品图片 -->
        <el-divider content-position="left">产品图片</el-divider>
        
        <el-form-item label="产品图片">
          <div class="image-upload-list">
            <div 
              v-for="(image, index) in currentProduct.images" 
              :key="index"
              class="image-item"
            >
              <img :src="image" alt="Product Image" />
              <div class="image-actions">
                <el-button type="text" @click="removeImage(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <el-upload
              class="image-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleImageUpload"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <div class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <div>添加图片</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 其他设置 -->
        <el-divider content-position="left">其他设置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number v-model="currentProduct.order" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch v-model="currentProduct.isActive" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProduct" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { request } from '../../../utils/request'
import { Plus, Edit, Delete, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'

interface Product {
  id: number
  name_en: string
  name_es: string
  name_ja: string
  description_en: string
  description_es: string
  description_ja: string
  category: string
  images: string[]
  specifications_en: string
  specifications_es: string
  specifications_ja: string
  certifications: string[]
  order: number
  isActive: boolean
}

interface Category {
  id: string
  name_en: string
  name_es: string
  name_ja: string
  order: number
}

const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const productFormRef = ref<FormInstance>()

const productList = ref<Product[]>([])
const categories = ref<Category[]>([])

const currentProduct = reactive<Product>({
  id: 0,
  name_en: '',
  name_es: '',
  name_ja: '',
  description_en: '',
  description_es: '',
  description_ja: '',
  category: '',
  images: [],
  specifications_en: '',
  specifications_es: '',
  specifications_ja: '',
  certifications: [],
  order: 1,
  isActive: true
})

const productRules: FormRules = {
  name_en: [{ required: true, message: '请输入英文产品名称', trigger: 'blur' }],
  name_es: [{ required: true, message: '请输入西班牙语产品名称', trigger: 'blur' }],
  name_ja: [{ required: true, message: '请输入日语产品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择产品分类', trigger: 'change' }],
  description_en: [{ required: true, message: '请输入英文产品描述', trigger: 'blur' }]
}

// 上传配置
const uploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/settings/upload/image`)
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('admin_token')
  return {
    'Authorization': `Bearer ${token}`
  }
})

// 获取产品列表和分类
const getProductsData = async () => {
  loading.value = true
  try {
    const response = await request.get('/settings') as any
    if (response.success) {
      console.log('获取设置数据:', response.data)
      
      // 处理产品列表
      const productsItem = response.data.find((item: any) => item.key === 'products_list')
      if (productsItem) {
        try {
          productList.value = JSON.parse(productsItem.value)
          console.log('产品列表数据:', productList.value)
        } catch {
          productList.value = []
        }
      } else {
        console.log('未找到 products_list 配置')
        productList.value = []
      }
      
      // 处理产品分类
      const categoriesItem = response.data.find((item: any) => item.key === 'products_categories')
      if (categoriesItem) {
        try {
          categories.value = JSON.parse(categoriesItem.value)
          console.log('产品分类数据:', categories.value)
        } catch {
          categories.value = []
        }
      } else {
        console.log('未找到 products_categories 配置')
        // 提供默认分类
        categories.value = [
          { id: 'primary', name_en: 'Primary Processed Fish', name_es: 'Pescado Procesado Primario', name_ja: '一次加工魚', order: 1 },
          { id: 'intermediate', name_en: 'Intermediate Processed Fish', name_es: 'Pescado Procesado Intermedio', name_ja: '中間加工魚', order: 2 },
          { id: 'premade', name_en: 'Pre-made Food', name_es: 'Comida Preparada', name_ja: 'プリメイド食品', order: 3 },
          { id: 'oem', name_en: 'OEM & ODM', name_es: 'OEM y ODM', name_ja: 'OEM・ODM', order: 4 }
        ]
      }
    }
  } catch (error) {
    console.error('获取产品数据失败:', error)
    ElMessage.error('获取产品数据失败')
  } finally {
    loading.value = false
  }
}

// 获取分类名称
const getCategoryName = (categoryId: string) => {
  const category = categories.value.find(cat => cat.id === categoryId)
  return category ? category.name_en : categoryId
}

// 获取分类标签类型
const getCategoryTagType = (categoryId: string) => {
  const types: Record<string, string> = {
    'primary': 'primary',
    'intermediate': 'success', 
    'premade': 'warning',
    'oem': 'info'
  }
  return types[categoryId] || 'info'
}

// 显示添加产品对话框
const showAddProduct = () => {
  isEdit.value = false
  resetCurrentProduct()
  dialogVisible.value = true
}

// 编辑产品
const editProduct = (product: Product) => {
  isEdit.value = true
  Object.assign(currentProduct, { ...product })
  dialogVisible.value = true
}

// 重置当前产品
const resetCurrentProduct = () => {
  Object.assign(currentProduct, {
    id: getNextId(),
    name_en: '',
    name_es: '',
    name_ja: '',
    description_en: '',
    description_es: '',
    description_ja: '',
    category: '',
    images: [],
    specifications_en: '',
    specifications_es: '',
    specifications_ja: '',
    certifications: [],
    order: getNextOrder(),
    isActive: true
  })
}

// 获取下一个ID
const getNextId = () => {
  return productList.value.length > 0 
    ? Math.max(...productList.value.map(p => p.id)) + 1 
    : 1
}

// 获取下一个排序号
const getNextOrder = () => {
  return productList.value.length > 0 
    ? Math.max(...productList.value.map(p => p.order)) + 1 
    : 1
}

// 图片上传成功
const handleImageUpload: UploadProps['onSuccess'] = (response) => {
  if (response.success) {
    currentProduct.images.push(response.data.url)
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 图片上传前检查
const beforeImageUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 移除图片
const removeImage = (index: number) => {
  currentProduct.images.splice(index, 1)
}

// 切换产品状态
const toggleProductStatus = async (product: Product) => {
  await saveProductList()
}

// 保存产品
const saveProduct = async () => {
  if (!productFormRef.value) return
  
  try {
    await productFormRef.value.validate()
    
    saving.value = true
    
    if (isEdit.value) {
      // 编辑现有产品
      const index = productList.value.findIndex(p => p.id === currentProduct.id)
      if (index !== -1) {
        productList.value[index] = { ...currentProduct }
      }
    } else {
      // 添加新产品
      productList.value.push({ ...currentProduct })
    }
    
    await saveProductList()
    
    dialogVisible.value = false
    ElMessage.success(isEdit.value ? '产品更新成功' : '产品添加成功')
  } catch (error) {
    console.error('保存产品失败:', error)
  } finally {
    saving.value = false
  }
}

// 删除产品
const deleteProduct = async (product: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${product.name_en}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = productList.value.findIndex(p => p.id === product.id)
    if (index !== -1) {
      productList.value.splice(index, 1)
      await saveProductList()
      ElMessage.success('产品删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 保存产品列表到后端
const saveProductList = async () => {
  try {
    const response = await request.post('/settings/batch', {
      settings: {
        products_list: JSON.stringify(productList.value)
      }
    }) as any

    if (!response.success) {
      throw new Error('保存失败')
    }
  } catch (error) {
    ElMessage.error('保存产品列表失败')
    throw error
  }
}

// 对话框关闭前处理
const handleDialogClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭对话框？未保存的更改将丢失。')
    .then(() => {
      done()
    })
    .catch(() => {
      // 取消关闭
    })
}

onMounted(async () => {
  await getProductsData()
  
  // 如果没有分类数据，提示用户初始化
  if (categories.value.length === 0 && productList.value.length === 0) {
    ElMessageBox.confirm(
      '检测到尚未初始化产品数据，是否现在初始化默认的产品配置？',
      '初始化产品数据',
      {
        confirmButtonText: '立即初始化',
        cancelButtonText: '稍后初始化',
        type: 'info'
      }
    ).then(async () => {
      try {
        const response = await request.post('/settings/init-products') as any
        if (response.success) {
          ElMessage.success('初始化成功')
          await getProductsData()
        }
      } catch (error) {
        ElMessage.error('初始化失败')
      }
    }).catch(() => {
      // 用户取消初始化
    })
  }
})
</script>

<style scoped>
.products-list-settings {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #c0c4cc;
}

.product-names {
  font-size: 12px;
  line-height: 1.4;
}

.certifications {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
}

.image-upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 2px;
  border-radius: 0 0 0 4px;
}

.image-uploader .upload-placeholder {
  width: 100px;
  height: 100px;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
  font-size: 12px;
  color: #8c939d;
}

.image-uploader .upload-placeholder:hover {
  border-color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>